<template>
  <video :style="setVideoSize"></video>
</template>

<script>
  export default {
    name: 'mvideo',
    props: {
      width: {
        type: Number,
        default: 300
      },
      height: {
        type: Number,
        default: 300
      }
    },
    created() {
      this.init()
    },
    computed: {
      setVideoSize() {
        return {
          width: `${this.width}px`,
          height: `${this.height}px`
        }
      }
    },
    methods: {
      init() {
        let _this = this
        let constraints = {
          audio: false, video: {width: _this.width, height: _this.height}
        }
        navigator.mediaDevices.getUserMedia(constraints).then(mediaStream => {
          let video = document.querySelector('video')
          let canvas = document.createElement('canvas')
          let ctx = canvas.getContext('2d')
          video.width = _this.width
          video.height = _this.height
          canvas.width = _this.width
          canvas.height = _this.height
          video.srcObject = mediaStream
          video.onloadedmetadata = function (e) {
            video.play()
          }
          setInterval(() => {
            ctx.clearRect(0, 0, _this.width, _this.height)
            ctx.drawImage(video, 0, 0, _this.width, _this.height)
            let data = canvas.toDataURL('image/jpg')
            _this.$emit('data', data)
          }, 500)
        }).catch(err => {
          this.$Message.error({
            content: `打开摄像头失败:${err.name},${err.message}`,
            duration: 5
          })
        })
      }
    }
  }
</script>

<style scoped>

</style>